import React, { useEffect, useRef } from 'react';
import { createRoot } from 'react-dom/client';

// 在文件顶部添加计数器
let modalCount = 0;
let scrolledY = 0;
let styleSheet
let originalStyles = {
  overflow: '',
  position: '',
  right: '',
  left: '',
  top: ''
};
// interface ModalFuncProps {
//   title?: string;
//   content?: React.ReactNode;
//   width?: number | string;
//   onOk?: () => void;
//   onCancel?: () => void;
//   okText?: string;
//   cancelText?: string;
// }
let styles = `
.wsj25121modal-mask{position: fixed;z-index: 1000;top: 0;right: 0;bottom: 0;left: 0;display: flex;align-items: center;justify-content: center;background-color: rgba(0, 0, 0, 0.45);}
.wsj25121modal-wrapper{border-radius: 8px;background: #fff;box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);}
.wsj25121modal-header{display: flex;align-items: center;justify-content: space-between;padding: 16px 24px;border-bottom: 1px solid #f0f0f0;}
.wsj25121modal-title{color: #333;font-size: 16px;font-weight: 500;}
.wsj25121modal-close{padding: 0 4px;cursor: pointer;color: #999;font-size: 20px;}
.wsj25121modal-content{overflow-y: auto;max-height: 70vh;padding: 24px;}
.wsj25121modal-footer{display: flex;justify-content: flex-end;padding: 10px 24px;border-top: 1px solid #f0f0f0;gap: 8px;}
.wsj25121modal-btn{padding: 4px 15px;cursor: pointer;border: 1px solid #d9d9d9;border-radius: 4px;background: #fff;font-size: 14px;}
.wsj25121modal-btn-primary{color: #fff;border-color: #1890ff;background: #1890ff;}`
// 在组件加载时注入样式
// const styleSheet = document.createElement('style');
// styleSheet.textContent = styles;
// document.head.appendChild(styleSheet);

// 创建弹窗组件
function ModalComponent({
  title = '提示',
  content,
  width = '90%',
  onOk,
  onCancel,
  okText = '确定',
  cancelText = '取消',
  close
}) {
  const elementRef = useRef(null);
  useEffect(() => {
    var rightGutter = window.innerWidth - document.documentElement.clientWidth
    const isFirstModal = modalCount === 0;
    if (isFirstModal) {
      scrolledY = window.scrollY;
      // 保存原始样式
      originalStyles = {
        overflow: document.body.style.overflow,
        position: document.body.style.position,
        right: document.body.style.right,
        left: document.body.style.left,
        top: document.body.style.top
      };
      document.body.style.overflow = 'hidden';
      document.body.style.position = 'fixed';
      document.body.style.right = rightGutter + 'px';
      document.body.style.left = 0;
      document.body.style.top = `-${scrolledY}px`;
    }
    modalCount++;
    // 淡入动画
    elementRef.current.animate([
      { opacity: 0, transform: 'translateY(-50px)' },
      { opacity: 1, transform: 'translateY(0)' }
    ], {
      duration: 800,
      easing: 'ease',
      fill: 'forwards'
    });
    return () => {
      modalCount--;
      // 只有最后一个模态框关闭时才恢复原始样式
      if (modalCount === 0) {
        document.body.style.overflow = originalStyles.overflow;
        document.body.style.position = originalStyles.position;
        document.body.style.right = originalStyles.right;
        document.body.style.left = originalStyles.left;
        document.body.style.top = originalStyles.top;
        window.scrollTo(0, scrolledY);
      }
    };
  }, []);

  const handleOk = async () => {
    if (onOk) {
      await onOk();
    }
    console.log('======modalCount', modalCount);
    if (modalCount === 1) {
      const animation = elementRef.current.animate([
        { opacity: 1, transform: 'translateY(0px)' },
        { opacity: 0, transform: 'translateY(-100px)' },
      ], {
        duration: 500,
        easing: 'linear',
        fill: 'forwards'
      });
      animation.onfinish = () => {
        close();
      };
    } else {
      console.log('======直接关');
      close();
    }
  };

  const handleCancel = async () => {
    if (onCancel) {
      await onCancel();
    }

    if (modalCount === 1) {
      const animation = elementRef.current.animate([
        { opacity: 1, transform: 'translateY(0px)' },
        { opacity: 0, transform: 'translateY(-100px)' },
      ], {
        duration: 2500,
        easing: 'ease',
        fill: 'forwards'
      });
      animation.onfinish = () => {
        close();
      };
    } else {
      close();
    }

  };

  const handleMaskClick = (e) => {
    // 确保点击的是遮罩层而不是其内部元素
    if (e.target.className === 'wsj25121modal-mask') {
      handleCancel();
    }
  };

  return (
    <div className="wsj25121modal-mask" onClick={handleMaskClick}>
      <div ref={elementRef} className="wsj25121modal-wrapper" style={{ width }}>
        <div className="wsj25121modal-header">
          <div className="wsj25121modal-title">{title}</div>
          <div className="wsj25121modal-close" onClick={handleCancel}>×</div>
        </div>
        <div className="wsj25121modal-content">
          {content}
        </div>
        <div className="wsj25121modal-footer">
          <button className="wsj25121modal-btn" onClick={handleCancel}>
            {cancelText}
          </button>
          <button className="wsj25121modal-btn wsj25121modal-btn-primary" onClick={handleOk}>
            {okText}
          </button>
        </div>
      </div>
    </div>
  );
};

// 创建函数式调用方法
const Modal = {
  show: (config) => {
    if (modalCount === 0) {
      styleSheet = document.createElement('style');
      styleSheet.textContent = styles;
      document.head.appendChild(styleSheet);
    }
    const div = document.createElement('div');
    document.body.appendChild(div);

    // 创建 root
    const root = createRoot(div);

    const close = () => {
      root.unmount();
      div.remove();
      if (modalCount === 0) {
        styleSheet.remove()
      }
    };

    // 使用 render 方法渲染组件
    root.render(<ModalComponent {...config} close={close} />);

    // 返回关闭方法，允许手动关闭
    return close;
  },
  // 其他方法（success、confirm、error 等）保持不变
  success: (config) => {
    return Modal.show({
      title: '成功',
      okText: '知道了',
      cancelText: null,
      ...config
    });
  },

  confirm: (config) => {
    return Modal.show({
      title: '确认',
      okText: '确认',
      cancelText: '取消',
      ...config
    });
  },
  error: (config) => {
    return Modal.show({
      title: '错误',
      okText: '知道了',
      cancelText: null,
      ...config
    });
  }
};

export default Modal;